import './public-path'
import { createApp } from 'vue'
import App from './App.vue'
import routes from './router'
import store from './store'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { createRouter, createWebHistory } from 'vue-router'
import registerGlobalModule from 'utils/global-register'
import { createI18n } from 'vue-i18n'
import Anchor from '@/components/Anchor'
import keysMixins from './hooks/useKeys'

let router = null
let instance = null

function render(props = {}) {
  const { container, routerBase, tlang } = props
  window.zcbFun = {
    ...window.zcbFun,
    keysMixins: keysMixins
  }
  
  // 创建i18n实例
  const i18n = createI18n({
    legacy: false,
    // globalInjection: true,
    locale: getLocale(tlang.messages),
    messages: tlang.messages
  })
  router = createRouter({
    history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? routerBase : process.env.BASE_URL),
    routes
  })
  instance = createApp(App)
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    instance.component(key, component)
  }
  for (const [key, component] of Object.entries(window.commonComponents)) {
    instance.component(key, component)
  }
  instance.component('Anchor', Anchor)
  // instance.use(hljsVuePlugin)
  instance.use(router)
  instance.use(store)
  instance.use(i18n)
  instance.use(ElementPlus)
  // instance.use(zcb, {
  //   hooks: {
  //     comon,
  //     tlang
  //   }
  // })
  instance.mount(container ? container.querySelector('#app') : '#app')
  instance.directive('resize', {
    mounted(el, binding) {
      // 这里使用debounce防抖处理，防抖的延时时间可以通过自定义指令的参数传过来，如`v-resize:300`表示300ms延时
      // 也可以将此处延时去掉，放在绑定的函数中自定义
      function debounce(fn, delay = 0) {
        let t = null
        return function() {
          if (t) {
            // clearTimeout(t)
          }
          const context = this
          const args = arguments
          // t = setTimeout(function() {
          fn.apply(context, args)
          // }, delay)
        }
      }
      el._resizer = new window.ResizeObserver(debounce(binding.value, Number(binding.arg) || 0))
      el._resizer.observe(el)
    },
    unmounted(el) {
      el._resizer.disconnect()
    }
  })
  // 创建按钮指令
  instance.directive('permission', props.permission)
}

if (!window.__POWERED_BY_QIANKUN__) {
  // 独立运行时，也注册一个名为global的store module
  registerGlobalModule(store)
  // 模拟登录后，存储用户信息到global module
  const userInfo = { name: '我是独立运行时名字叫张三' } // 假设登录后取到的用户信息
  store.commit('global/setGlobalState', { user: userInfo })
  render()
}
export async function bootstrap() {}
// 首次创建微应用 挂载
export async function mount(props) {
  // 初始化拿到主应用的付给子应用的vuex
  // props.getGlobalState('user').language 拿到主应用的语言
  // props.getGlobalState('user').toBeApprovedNum 拿到主应用待提交的数
  store.dispatch('apps/changeLanguage', props.getGlobalState('user').language || 'zh-cn')
  store.dispatch('apps/changeToBeApprovedNum', props.getGlobalState('user').toBeApprovedNum || 0)

  // 创建 微应用 vuex global状态管理
  registerGlobalModule(store, props)
  // qiankun 监听主应用状态发生变化
  props.onGlobalStateChange((state, prev) => {
    // 监听全局国际语言变化，并映射到微应用自己的store
    state.language ? store.dispatch('apps/changeLanguage', state.language) : ''
    state.user.toBeApprovedNum ? store.dispatch('apps/changeToBeApprovedNum', state.user.toBeApprovedNum) : ''
  })
  render(props)
}

export const getLocale = (messages) => {
  // 读取localStorage存入的当前语言
  const localLanguage = localStorage.getItem('language') || ''
  // 如果有返回当前语言
  if (localLanguage) {
    return localLanguage
  }
  // 如果没有，获取系统语言
  const language = navigator.language.toLowerCase()
  // 获取messages 语言 遍历
  for (const locale of Object.keys(messages)) {
    // 如果messsage 包里面有系统语言返回
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  // 默认语言 简体中文
  return 'zh-cn'
}
export async function unmount() {
  instance.unmount()
  instance._container.innerHTML = ''
  instance = null
  router = null
}
